import 'package:flutter/foundation.dart';
import 'package:my_flutter_core/models/error.dart';
import 'package:my_flutter_core/services/http_request_service.dart';
import 'package:my_flutter_core/utils/device_utils.dart';
import 'package:my_flutter_core/utils/system_utils.dart';

class AppErrorReport {
  final String _url = '/app-error-report';

  /// Sends error report to remote server.
  Future<void> send(Object error, StackTrace stackTrace) async {
    final errorMessage = error.toString().toLowerCase();

    // Only sends report to server in release mode.
    if (kReleaseMode) {
      // Checks if we need to report this error.
      if (_needToReport(error, stackTrace)) {
        await HttpRequestService().post(
          '$_url/send',
          body: {
            'errorMessage': errorMessage,
            'stackTrace': stackTrace.toString(),
            'deviceInfo': (await getDeviceInfo())!.toJson(),
            'systemInfo': (await getSystemInfo()).toJson(),
          },
        );
      }
    } else if (kDebugMode) {
      print(
        'errorMessage: $errorMessage. stackTrace: ${stackTrace.toString()}',
      );
    }
  }

  /// Checks if we need to report this error.
  ///
  /// We don't need to report [UnauthorizedError] and [ForbiddenError].
  /// Also flutter_pagewise.dart causes ChangeNotifier error sometimes. We need to ignore it.
  bool _needToReport(Object error, StackTrace stackTrace) {
    return error is! UnauthorizedError &&
        error is! ForbiddenError &&
        !stackTrace.toString().contains('flutter_pagewise');
  }
}
